package com.bianmaba;

import com.bianmaba.beans.datacollection.TaskInstance;
import com.bianmaba.commons.bean.result.OperationResult;
import com.bianmaba.jobs.supports.CollectionRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutorService;

@RestController
@RequestMapping("dts")
@Scope("singleton")
public class DataCollectionController {
    private boolean stoped = false;
    @Autowired
    private ExecutorService executorService;

    @RequestMapping(value = "collection")
    public OperationResult<Boolean> collection(@RequestBody CollectionRequest collectionRequest, HttpServletRequest servletRequest) {
        stoped = false;
        System.out.println("采集请求：" + collectionRequest.toString());

        String message = String.format("采集请求已经收到：URL=%s,parameters=%s", servletRequest.getRequestURL(), collectionRequest.toString());
        return OperationResult.of(true).setData(true).setResult(message);
    }

    @RequestMapping("status")
    public OperationResult<Integer> status(String taskInstanceId) throws InterruptedException {
        if (stoped) {
            return OperationResult.of(true).setData(TaskInstance.Status.TERMINATED.getIndex());
        } else {
            return OperationResult.of(true).setData(TaskInstance.Status.RUNNING.getIndex());
        }
    }

    @RequestMapping("stop")
    public OperationResult<Integer> stop(String taskInstanceId, HttpServletRequest servletRequest) throws InterruptedException {
        Thread.sleep(3000);
        String message = String.format("终止采集请求已经收到：URL=%s,taskInstanceId=%s", servletRequest.getRequestURL(), taskInstanceId);
        this.stoped = true;
        return OperationResult.of(true).setData(true).setResult(message);
    }

}
